#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
改进的车型名称提取脚本
"""

import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup

def improved_model_name_extraction():
    """改进的车型名称提取"""
    url = "https://www.ford.co.uk/cars/puma#models"
    
    # 设置Chrome选项
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")
    chrome_options.add_argument("--window-size=1920,1080")
    chrome_options.add_argument("--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
    
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=chrome_options)
    
    try:
        print(f"访问页面: {url}")
        driver.get(url)
        time.sleep(5)
        
        # 滚动到页面底部
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(2)
        
        # 获取页面HTML
        html = driver.page_source
        soup = BeautifulSoup(html, 'html.parser')
        
        # 找到比较部分
        compare_heading = soup.find('h2', string=lambda text: text and 'Compare Ford Puma' in text)
        if not compare_heading:
            print("未找到比较部分")
            return
            
        print("找到比较部分")
        
        # 找到比较部分的父容器
        compare_container = compare_heading.find_parent()
        
        # 查找所有 See Full Specs 按钮
        spec_buttons = compare_container.find_all('button', class_='full-spec-cta tertiary-cta')
        print(f"找到 {len(spec_buttons)} 个 See Full Specs 按钮")
        
        model_info = []
        
        for i, button in enumerate(spec_buttons):
            print(f"\\n=== 分析第 {i+1} 个车型 ===")
            
            # 找到按钮的卡片容器
            card_container = button.find_parent('div', class_='card-container')
            if not card_container:
                print("未找到卡片容器")
                continue
                
            # 方法1: 查找Recommended OTR Price附近的信息
            model_name = None
            price_elements = card_container.find_all(string=lambda text: text and 'Recommended OTR Price' in text)
            
            if price_elements:
                for price_elem in price_elements:
                    # 查找价格后面的描述
                    parent = price_elem.parent
                    next_siblings = parent.find_next_siblings()
                    
                    for sibling in next_siblings:
                        text = sibling.get_text().strip()
                        if any(keyword in text for keyword in ['Titanium', 'ST-Line', 'ST', 'Sound Edition', 'Active']):
                            # 提取关键词
                            for keyword in ['Titanium', 'ST-Line', 'ST', 'Sound Edition', 'Active']:
                                if keyword in text:
                                    model_name = keyword
                                    break
                            if model_name:
                                break
                    if model_name:
                        break
            
            # 方法2: 查找发动机描述中的信息
            if not model_name:
                engine_texts = card_container.find_all(string=lambda text: text and ('EcoBoost' in text or 'mHEV' in text))
                for eng_text in engine_texts:
                    eng_parent = eng_text.parent
                    # 查找同一级别的兄弟元素
                    for sibling in eng_parent.find_next_siblings():
                        text = sibling.get_text().strip()
                        if any(keyword in text for keyword in ['Titanium', 'ST-Line', 'ST', 'Sound Edition']):
                            for keyword in ['Titanium', 'ST-Line', 'ST', 'Sound Edition']:
                                if keyword in text:
                                    model_name = keyword
                                    break
                            if model_name:
                                break
                    if model_name:
                        break
            
            # 方法3: 在整个卡片中搜索车型名称
            if not model_name:
                card_text = card_container.get_text()
                model_keywords = ['Titanium', 'ST-Line X', 'ST-Line', 'ST', 'Sound Edition', 'Active']
                for keyword in model_keywords:
                    if keyword in card_text:
                        model_name = keyword
                        break
            
            # 方法4: 查找图片alt文本中的信息
            if not model_name:
                images = card_container.find_all('img')
                for img in images:
                    alt_text = img.get('alt', '')
                    src_text = img.get('src', '')
                    if alt_text:
                        for keyword in ['Titanium', 'ST-Line', 'ST', 'Sound']:
                            if keyword.lower() in alt_text.lower():
                                model_name = keyword
                                break
                    if not model_name and src_text:
                        for keyword in ['titanium', 'st-line', 'st_line']:
                            if keyword in src_text.lower():
                                model_name = keyword.replace('_', '-').title()
                                break
                    if model_name:
                        break
            
            if not model_name:
                model_name = f"Unknown_Model_{i+1}"
            
            print(f"提取的车型名称: {model_name}")
            
            # 保存卡片HTML进行调试
            with open(f'debug_card_{i+1}.html', 'w', encoding='utf-8') as f:
                f.write(str(card_container))
            
            model_info.append({
                'index': i+1,
                'name': model_name,
                'button_text': button.get_text().strip()
            })
        
        print(f"\\n=== 提取结果汇总 ===")
        for info in model_info:
            print(f"{info['index']}. {info['name']} - {info['button_text']}")
        
        return model_info
        
    except Exception as e:
        print(f"错误: {e}")
        import traceback
        traceback.print_exc()
        return []
    finally:
        driver.quit()

if __name__ == "__main__":
    improved_model_name_extraction()
